<template>
  <view class="detail-page" :style="{ backgroundColor: isLoading ? '#000' : '' }">
    <!-- 加载中 -->
    <view class="loading-container" v-if="isLoading">
      <view class="loading-spinner" style="font-size: 40px; color: #fff;">⏳</view>
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 壁纸预览 -->
    <view class="wallpaper-preview" v-if="!isLoading">
      <image 
        :src="wallpaperDetail.imageUrl" 
        mode="aspectFit" 
        class="wallpaper-image"
        @load="handleImageLoad"
        @error="handleImageError"
      />
      
      <!-- 顶部信息栏 -->
      <view class="top-bar">
        <view class="back-btn" @click="navigateBack">
          <view class="icon icon-left" style="font-size: 28px; color: #fff;">‹</view>
        </view>
        <view class="wallpaper-info">
          <text class="wallpaper-title">{{ wallpaperDetail.title }}</text>
          <text class="wallpaper-stats">
            <view class="icon icon-download" style="font-size: 14px; color: #fff;">⬇️</view>
            {{ wallpaperDetail.downloads || 0 }} · 
            <view class="icon icon-heart" style="font-size: 14px; color: #fff;">🤍</view>
            {{ wallpaperDetail.favorites || 0 }}
          </text>
        </view>
      </view>
      
      <!-- 底部操作栏 -->
      <view class="bottom-bar">
        <view class="action-buttons">
          <view class="action-btn" @click="handleFavorite">
            <view 
              class="icon icon-heart"
              :style="{ color: wallpaperDetail.is_favorite ? '#ff4d4f' : '#fff', fontSize: '32px' }" 
            >
              {{ wallpaperDetail.is_favorite ? '❤️' : '🤍' }}
            </view>
            <text class="action-text">{{ wallpaperDetail.is_favorite ? '已收藏' : '收藏' }}</text>
          </view>
          
          <view class="action-btn primary" @click="handleDownload">
            <view class="icon icon-download" style="font-size: 32px; color: #fff;">⬇️</view>
            <text class="action-text">下载</text>
          </view>
          
          <view class="action-btn" @click="handleSetWallpaper">
            <view class="icon icon-image" style="font-size: 32px; color: #fff;">🖼️</view>
            <text class="action-text">设为壁纸</text>
          </view>
        </view>
      </view>
      
      <!-- 标签 -->
      <view class="tags-container" v-if="wallpaperDetail.tags && wallpaperDetail.tags.length > 0">
        <view 
          v-for="(tag, index) in wallpaperDetail.tags" 
          :key="index"
          class="tag"
          @click="searchByTag(tag)"
        >
          # {{ tag }}
        </view>
      </view>
    </view>
    
    <!-- 图片加载失败 -->
    <view class="error-container" v-if="!isLoading && imageError">
      <view class="icon icon-image" style="font-size: 64px; color: #666;">🖼️</view>
      <text class="error-text">图片加载失败</text>
      <button class="retry-btn" @click="loadWallpaperDetail">重试</button>
    </view>
  </view>
</template>

<script setup>
import { nextTick, ref } from 'vue';
import {onLoad, onShow} from "@dcloudio/uni-app"
import { useToken } from '../../common/token.js';

// 使用token composable
const { token, loadToken, isValid } = useToken();

// 路由参数
const id = ref('');

// 通过onLoad获取路由参数
onLoad((options) => {
	console.log({options});
  id.value = options.id || '';
  loadWallpaperDetail();
  updatewall();
});
const downloadtempFilePath = ref('')
// 状态管理
const isLoading = ref(true);
const imageError = ref(false);
const wallpaperDetail = ref({
  _id: '',
  title: '',
  imageUrl: '',
  downloads: 0,
  favorites: 0,
  is_favorite: false,
  tags: []
});

// 加载壁纸详情
const loadWallpaperDetail = async () => {
	console.log('??????',id.value);
  if (!id.value) {
    uni.showToast({ title: '壁纸ID无效', icon: 'none' });
    uni.navigateBack();
    return;
  }
  
  try {
    isLoading.value = true;
    imageError.value = false;
    
    // 尝试调用云函数获取详情
    try {
      const res = await uniCloud.callFunction({
        name: 'getDetail',
        data: { id: id.value }
      });
      console.log('云函数调用数据',res);
      if (res && res.result && res.result.code === 0) {
        wallpaperDetail.value = res.result.data[0];
      } else {
        console.log('云函数调用失败或无数据，',res);
      }
    } catch (cloudError) {
      console.log('获取壁纸详情失败，:', cloudError);
    }
  } catch (error) {
    console.error('加载壁纸详情失败:', error);
    imageError.value = true;
    // 即使出错也显示模拟数据，避免空白页面
  } finally {
    isLoading.value = false;
  }
};
// 更新壁纸  1. viewswall 查看  2.downloadswall 下载 3.favoriteswall 收藏
const updatewall = async (queryaction) => {
  try {
    const action = queryaction || 'viewswall';
    console.log('调用updateWallpaper，操作类型:', action, '壁纸ID:', id.value);
    
    const res = await uniCloud.callFunction({
      name: 'updateWallpaper',
      data: {
        action: action,
        id: id.value
      }
    });
    
    console.log('updateWallpaper返回结果:', res);
    
    // 重新加载壁纸详情以更新数据
    if (res.result && (res.result.code === 0 || !res.result.code)) {
      await loadWallpaperDetail();
    }
  } catch (error) {
    console.error('调用updateWallpaper失败:', error);
  }
}
// 图片加载完成
const handleImageLoad = () => {
  console.log('图片加载完成');
};

// 图片加载失败
const handleImageError = () => {
  console.error('图片加载失败');
  imageError.value = true;
  isLoading.value = false;
};

// 返回上一页
const navigateBack = () => {
  uni.navigateBack();
};

// 处理收藏
const handleFavorite = async () => {
  // await loadToken(); // 确保token已加载
  // if (!isValid()) {
  //   uni.showToast({ title: '请先登录', icon: 'none' });
  //   return;
  // }
  try {
    // 实际调用收藏云函数
    // const res = await uniCloud.callFunction({
    //   name: 'toggle',
    //   data: { 
    //     wallpaper_id: wallpaperDetail.value._id,
    //     uid: uniCloud.getCurrentUserInfo().uid
    //   }
    // });
    const res = await uniCloud.callFunction({
      name: 'toggle',
      data: {
          wallpaper_id: wallpaperDetail.value._id,
          uid: uniCloud.getCurrentUserInfo().uid
        }
    });
    console.log('收藏操作结果:', res);
    
    if (res.result.code === 0) {
      // 成功更新收藏状态
      wallpaperDetail.value.is_favorite = res.result.data.is_favorite;
      wallpaperDetail.value.favorites += res.result.data.is_favorite ? 1 : -1;
	  updatewall('favoriteswall');
      uni.showToast({
        title: res.result.message || (res.result.data.is_favorite ? '收藏成功' : '取消收藏'),
        icon: 'success'
      });
    } else if (res.result.code === 401) {
      // 处理认证错误
      if (res.result.tokenStatus === 'expired' || res.result.tokenStatus === 'error') {
        console.log('token可能过期，尝试刷新...');
        // loadToken();
        // await new Promise(resolve => setTimeout(resolve, 100));
       
      } else {
        uni.navigateTo({
          url: '/uni_modules/uni-id-pages/pages/login/login-withoutpwd'
        });
      }
    } else {
      // 其他错误
      uni.showToast({
        title: res.result.message || '操作失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('收藏操作失败:', error);
    uni.showToast({ title: '网络错误，请重试', icon: 'none' });
  }
};

// 处理下载
const handleDownload = async () => {
  try {
    // 请求相册权限
    const { authSetting } = await uni.getSetting();
    if (!authSetting['scope.writePhotosAlbum']) {
      const { authSetting: newAuthSetting } = await uni.authorize({
        scope: 'scope.writePhotosAlbum',
        fail: () => {
          uni.showToast({ title: '需要相册权限才能下载', icon: 'none' });
          return Promise.reject('用户拒绝授权');
        }
      });
      
      if (!newAuthSetting['scope.writePhotosAlbum']) {
        uni.showToast({ title: '请在设置中打开相册权限', icon: 'none' });
        return;
      }
    }
    
    uni.showLoading({ title: '下载中...' });
    console.log('图片路径：', wallpaperDetail.value.imageUrl,);
    console.log('图片_id：', wallpaperDetail.value._id);
    // 下载图片
    const downloadResult = await uni.downloadFile({
      url: wallpaperDetail.value.imageUrl,
      success: (res) => {
		  console.log('chengg ',res);
        if (res.statusCode === 200) {
			// 保存到相册
			 uni.saveImageToPhotosAlbum({
			  // filePath: downloadResult.tempFilePath,
			  filePath:res.tempFilePath,
			  success: (res) => {
			  	if (res.statusCode==200) {
					 uni.showToast({ title: '保存成功', icon: 'none' });
			  		updatewall('downloadswall');
			  	}
			  },
			  fail: (err) => {
				  console.log('保存失败',err);
				 uni.showToast({ title: '保存失败', icon: 'none' });
			    throw new Error('保存失败');
			  }
			});
          return res.tempFilePath;
        } else {
          throw new Error('下载失败');
        }
      },
      fail: () => {
        throw new Error('下载失败');
      }
    });
   
    
    // 记录下载行为
    try {
      await uniCloud.callFunction({
        name: 'recordDownload',
        data: {
          wallpaper_id: wallpaperDetail.value._id,
          // uniIdToken: token.value || '',
		  uid:uniCloud.getCurrentUserInfo().uid
        }
      });
    } catch (recordError) {
      console.log('记录下载失败，但不影响下载体验:', recordError);
    }
    
    // 更新下载次数
    wallpaperDetail.value.downloads++;
    
    uni.showToast({ title: '下载成功', icon: 'success' });
  } catch (error) {
    console.error('下载失败:', error);
    uni.showToast({ title: '下载失败', icon: 'none' });
  } finally {
    uni.hideLoading();
  }
};

// 设置壁纸（实际需要原生插件支持）
const handleSetWallpaper = () => {
  uni.showModal({
    title: '提示',
    content: '设置壁纸功能需要原生插件支持',
    showCancel: false
  });
};

// 按标签搜索
const searchByTag = (tag) => {
  uni.navigateTo({
    url: `/pages/search/search?keyword=${encodeURIComponent(tag)}`
  });
};
</script>

<style scoped lang="less">
.icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.loading-spinner {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
.detail-page {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  
  .loading-container {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #000;
    
    .loading-text {
      color: #fff;
      margin-top: 16px;
      font-size: 16px;
    }
  }
  
  .wallpaper-preview {
    position: relative;
    width: 100%;
    height: 100%;
    
    .wallpaper-image {
      width: 100%;
      height: 100%;
    }
    
    .top-bar {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      padding: 40px 16px 20px;
      background: linear-gradient(to bottom, rgba(0, 0, 0, 0.7), transparent);
      display: flex;
      align-items: flex-end;
      
      .back-btn {
        margin-right: 12px;
        padding: 8px;
      }
      
      .wallpaper-info {
        flex: 1;
        
        .wallpaper-title {
          color: #fff;
          font-size: 18px;
          font-weight: 500;
          display: block;
          margin-bottom: 4px;
        }
        
        .wallpaper-stats {
          color: rgba(255, 255, 255, 0.8);
          font-size: 14px;
        }
      }
    }
    
    .bottom-bar {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      padding: 20px 16px 40px;
      background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
      
      .action-buttons {
        display: flex;
        justify-content: space-around;
        align-items: center;
        
        .action-btn {
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 8px;
          padding: 12px 20px;
          
          &.primary {
            // background-color: rgba(0, 122, 255, 0.8);
            border-radius: 24px;
            
            .action-text {
              color: #fff;
            }
          }
          
          .action-text {
            color: rgba(255, 255, 255, 0.9);
            font-size: 14px;
          }
        }
      }
    }
    
    .tags-container {
      position: absolute;
      bottom: 140px;
      left: 16px;
      right: 16px;
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      
      .tag {
        padding: 6px 12px;
        background-color: rgba(0, 0, 0, 0.5);
        color: #fff;
        border-radius: 16px;
        font-size: 13px;
        
        &:active {
          background-color: rgba(0, 0, 0, 0.7);
        }
      }
    }
  }
  
  .error-container {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #f5f5f5;
    
    .error-text {
      color: #666;
      margin: 16px 0;
      font-size: 16px;
    }
    
    .retry-btn {
      background-color: #007aff;
      color: #fff;
      border: none;
      padding: 8px 24px;
      border-radius: 20px;
    }
  }
}
</style>